local mysql = require "resty.mysql"
local cjson = require "cjson"

local _M = {}

function _M.connect_to_mysql()
    local db, err = mysql:new()
    if not db then
        ngx.log(ngx.ERR, "failed to instantiate mysql: ", err)
        return nil
    end

    local ok, err, errno, sqlstate = db:connect{
        host = "127.0.0.1",
        port = 6033,
        database = "hello-im",
        user = "root",
        password = "Mina0708##",
        charset = "utf8",
        max_packet_size = 1024 * 1024,
    }

    if not ok then
        ngx.log(ngx.ERR, "failed to connect to mysql: ", err)
        return nil
    end

    return db
end

function _M.register(username, password)
    local db = _M.connect_to_mysql()
    if not db then
        return nil, "Database connection failed"
    end

    local hashed_password = ngx.md5(password)
    local sql = string.format(
        "INSERT INTO users (username, password) VALUES ('%s', '%s')",
        username, hashed_password
    )

    local res, err, errno, sqlstate = db:query(sql)
    if not res then
        ngx.log(ngx.ERR, "failed to insert user: ", err)
        return nil, "Registration failed"
    end

    db:close()
    return true, "Registration successful"
end

function _M.login(username, password)
    local db = _M.connect_to_mysql()
    if not db then
        return nil, "Database connection failed"
    end

    local hashed_password = ngx.md5(password)
    local sql = string.format(
        "SELECT id FROM users WHERE username='%s' AND password='%s'",
        username, hashed_password
    )

    local res, err, errno, sqlstate = db:query(sql)
    if not res or #res == 0 then
        return nil, "Invalid username or password"
    end

    db:close()
    return res[1].id, "Login successful"
end

return _M
